package org.misty.spring.redis.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.misty.spring.redis.filter.RedisBloomFilter;
import org.misty.spring.redis.service.MockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class MockServiceImpl implements MockService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RedisBloomFilter bloomFilter;

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> findByCache(int id) {
        var obj = valueOps().get(String.valueOf(id));
        if (obj == null) {
            obj = findDB(id);
            if (obj != null) {
                valueOps().set(String.valueOf(id), obj);
            }
        }
        return (Map<String, Object>) obj;
    }

    @Override
    public Map<String, Object> findByBloom(int id) {
        if (bloomFilter.isExists(String.valueOf(id))) {
            return findByCache(id);
        }
        return null;
    }

    private Map<String, Object> findDB(int id) {
        log.info("查询数据库");
        if (id > 0 && id <= 10) {
            var map = new HashMap<String, Object>();
            map.put("id", id);
            map.put("field1", "value1");
            map.put("field2", "value2");
            return map;
        }
        return null;
    }

    private ValueOperations<String, Object> valueOps() {
        return this.redisTemplate.opsForValue();
    }
}
